import { ref, onMounted, onBeforeUnmount } from "vue";

const useWebSocket = (url) => {
  const socket = ref(null);
  const messages = ref([]);
  const isConnected = ref(false);

  const connect = () => {
    socket.value = new WebSocket(url);

    socket.value.onopen = () => {
      isConnected.value = true;
    };

    socket.value.onmessage = (event) => {
      messages.value.push(event.data);
      ElNotification({
        title: "新消息",
        message: event.data,
        type: "primary",
        position: "bottom-right",
        onClick: () => {
          // 点击通知的处理逻辑
        },
      });
    };

    socket.value.onclose = () => {
      isConnected.value = false;
      // 可以在这里添加重连逻辑
    };

    socket.value.onerror = (error) => {
      console.error("WebSocket error:", error);
    };
  };

  const sendMessage = (message) => {
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
      socket.value.send(message);
    }
  };

  onMounted(() => {
    connect();
  });

  onBeforeUnmount(() => {
    if (socket.value) {
      socket.value.close();
    }
  });

  return {
    socket,
    messages,
    isConnected,
    sendMessage,
  };
};

export default useWebSocket;
